package com.demo.openpdfdemo.service;

import com.demo.openpdfdemo.model.UserModel;
import com.demo.openpdfdemo.pdfCreator.PdfPageEventListener;
import com.demo.openpdfdemo.pdfCreator.UserInfoPdfCreator;
import com.demo.openpdfdemo.pdfCreator.core.AbstractPdfCreator;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    /**
     * 用户信息打印
     *
     * @param response
     * @throws IOException
     */
    public void printUserInfo(HttpServletResponse response) throws IOException {
        UserModel model = new UserModel();
        model.setName("张三");
        model.setAge(12);
        model.setEducation("本科");
        model.setNational("汉族");
        model.setSex("男");
        model.setNativePlace("北京市");
        model.setRemark("<p>此人学习习惯很好</p><p><strong>非常优秀</strong></p>爱好<ul><li>篮球</li><li>乒乓球</li></ul><table border=\"1\" style=\"border-collapse: collapse\"><tr><th style=\"width: 30%;color: aquamarine\">毕业学校</th> <th style=\"width: 30%\">专业</th> </tr><tr><td style=\"width: 30%\">清华</td> <td style=\"width: 30%\">计算机</td> </tr></table>");
        Map<String, Object> map = new HashMap<>();
        map.put("data", model);
        String signature = "签字：________________" + "日期：" + LocalDate.now();
        PdfPageEventListener listener = PdfPageEventListener.build().setNoticeCode("0001").setSignature(signature).build();
        AbstractPdfCreator pdfCreator = new UserInfoPdfCreator();
        ByteArrayOutputStream outputStream = pdfCreator.init(listener).creator(map);
        response.reset();
        response.setHeader("Content-Type", "application/pdf");
        response.setHeader("content-disposition", "attachment;filename=111.pdf");
        response.setContentLength(outputStream.size());
        OutputStream output = response.getOutputStream();
        outputStream.writeTo(output);
        output.flush();
        output.close();
    }
}
